package com.cwf.quality.common.strategy.filter;

import com.cwf.quality.common.enums.DataCheckFilterEnum;
import com.cwf.quality.model.dto.QualityResultInfo;
import com.cwf.quality.model.dto.datacheck.result.ValueCodeTableCheckResult;
import com.cwf.quality.model.dto.datacheck.rule.CheckRuleInfo;
import com.cwf.quality.model.dto.datacheck.rule.DataCheckRuleInfo;
import com.cwf.quality.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ValueCodeTableCheckFilter implements IDataCheckFilter {

    /**
     * 字段数据字典代码表校验
     *
     * @param dataCheckRuleInfo
     * @return
     */
    @Override
    public QualityResultInfo<ValueCodeTableCheckResult> checkData(DataCheckRuleInfo dataCheckRuleInfo) {
        SqlUtils sqlUtils = dataCheckRuleInfo.getSqlUtils();

        Map<String, List<ValueCodeTableCheckResult.ValueCodeTableCount>> valueCodeTableCountMap = new HashMap<>();

        List<CheckRuleInfo.ColumnCodeTable> columnCodeTableList = dataCheckRuleInfo.getCheckRuleInfo().getColumnCodeTableList();
        for (CheckRuleInfo.ColumnCodeTable columnCodeTable : columnCodeTableList) {
            String columnName = columnCodeTable.getColumnName();

            String sql = DataCheckFilterEnum.VALUE_CODE_TABLE_CHECK.getSql()
                    .replace("{table}", dataCheckRuleInfo.getTableName())
                    .replace("{column}", columnName)
                    .replace("{codeTable}", columnCodeTable.getCodeTableName())
                    .replace("{codeTableColumn}", columnCodeTable.getCodeTableColumnName());


            List<Map<String, Object>> mapList = sqlUtils.query4List(sql, -1);

            List<ValueCodeTableCheckResult.ValueCodeTableCount> valueCodeTableCountList = new ArrayList<>();
            for (Map<String, Object> map : mapList) {
                Object columnValue = map.get(columnName);
                Long count = (Long) map.get("not_in_code_table_count");
                valueCodeTableCountList.add(new ValueCodeTableCheckResult.ValueCodeTableCount(columnValue, count));
            }
            valueCodeTableCountMap.put(columnName, valueCodeTableCountList);
        }

        QualityResultInfo qualityResultInfo = QualityResultInfo.builder()
                .code(0)
                .msg("成功")
                .result(new ValueCodeTableCheckResult(valueCodeTableCountMap))
                .build();
        return qualityResultInfo;
    }
}
